<template>
  <div class="login">
    <div class="form">
      <div class="title">重置密码</div>
      <a-form ref="formLogin" id="formLogin" class="user-layout-login" :model="formData" :rules="rules">
        <a-tabs
          v-model:activeKey="formData.type"
          :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
          style="margin-bottom: 10px"
        >
          <a-tab-pane :key="1" tab="手机号" />
          <!--          <a-tab-pane :key="2" tab="邮箱" /> -->
        </a-tabs>
        <a-form-item name="account">
          <a-input v-model:value="formData.account" type="text" placeholder="请输入账号">
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
        </a-form-item>
        <a-form-item name="phone" v-if="formData.type == 1">
          <a-input v-model:value="formData.phone" type="text" placeholder="请输入手机号">
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
          </a-input>
        </a-form-item>
        <a-form-item name="email" v-if="formData.type == 2">
          <a-input v-model:value="formData.email" placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item name="code">
          <a-row :gutter="10" type="flex" align="middle">
            <a-col :span="16">
              <a-input v-model:value="formData.code" type="text" placeholder="请输入验证码" :disabled="codeReadonly">
                <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input>
            </a-col>
            <a-col :span="8">
              <a-button
                :disabled="state.smsSendBtn"
                @click.stop.prevent="getCaptcha"
                v-text="(!state.smsSendBtn && '发送验证码') || state.time + ' s'"
              />
            </a-col>
          </a-row>
        </a-form-item>
        <a-alert v-if="state.loginError" type="error" showIcon style="margin-bottom: 24px" message="账号或者密码错误" />
        <div style="margin-bottom: 10px; clear: both; overflow: hidden">
          <router-link :to="{ name: 'login' }" style="float: right">返回登录</router-link>
        </div>
        <a-form-item>
          <a-button
            size="large"
            type="primary"
            class="login-button"
            style="width: 100%"
            :loading="state.loginBtn"
            :disabled="state.loginBtn"
            @click="handleSubmit"
            >重置密码</a-button
          >
        </a-form-item>
      </a-form>
    </div>
    <div class="copyright">{{ copyright }}</div>
  </div>
</template>

<script>
import { logout } from './utils.js';
import { getCopyright, resetUserPassword, sendResetPasswordEmail, sendRestPasswordAuthCode } from '../../api/index.js';
import { handleCommonResult } from '../../utils/resolver.js';

export default {
  name: 'Recover',
  data() {
    return {
      copyright: '',
      formData: { type: 1 },
      rules: {
        account: { required: true, message: '请输入账号' },
        phone: {
          required: true,
          pattern: /^1[34578]\d{9}$/,
          message: '请输入手机号',
        },
        email: {
          required: true,
          pattern: /^\w+@\w+\.\w+$/,
          message: '请输入邮箱',
        },
        code: { required: true, message: '请输入验证码' },
      },
      type: 1,
      form: {},
      codeReadonly: true,
      state: {
        time: 60,
        loginError: false, //登录错误提示
        loginBtn: false,
        smsSendBtn: false,
      },
    };
  },
  created() {
    this.getCopyrightDataAsync();
  },
  methods: {
    async getCopyrightDataAsync() {
      const data = await handleCommonResult(getCopyright, {
        silent: true,
        defaultValue: null,
      });
      if (data !== null) this.copyright = data;
    },
    async getCaptcha(e) {
      const { state } = this;
      const { type, account, phone, email } = this.formData;
      if (!account) {
        return this.$message.warn('请输入账号');
      }
      if (type == 1 && !phone) {
        return this.$message.warn('请输入手机号');
      }
      if (type == 2 && !email) {
        return this.$message.warn('请输入邮箱');
      }
      state.smsSendBtn = true;
      const interval = window.setInterval(() => {
        if (state.time-- <= 0) {
          state.time = 60;
          state.smsSendBtn = false;
          window.clearInterval(interval);
        }
      }, 1000);
      const hide = this.$message.loading('验证码发送中..', 0);
      const api = type === 1 ? sendRestPasswordAuthCode : sendResetPasswordEmail;
      const params = { account: account, [type == 1 ? 'phone' : 'email']: type == 1 ? phone : email };
      const res = await api(params);
      setTimeout(hide, 1);
      if (res && res.code == 200) {
        this.codeReadonly = false;
        this.$message.success(res.msg || '验证码发送成功');
      } else {
        this.codeReadonly = true;
        clearInterval(interval);
        state.time = 60;
        state.smsSendBtn = false;
        this.$message.error(res.msg || '请求出现错误，请稍后再试');
      }
    },
    async handleSubmit() {
      const { state } = this;
      const { type, account, phone, email } = this.formData;
      state.loginBtn = true;
      const validate = await this.$refs.formLogin.validate();
      if (!validate) {
        state.loginBtn = false;
        return;
      }
      this.formData.phone = type == 1 ? this.formData.phone : this.formData.email;
      delete this.formData.email;
      const loginParams = { ...this.formData };
      resetUserPassword(loginParams)
        .then((res) => {
          if (res && res.code == 200) {
            this.onSuccess(res);
          } else {
            this.state.loginError = true;
            this.$message.error(res.msg || '请求出现错误，请稍后再试');
          }
        })
        .catch((err) => this.requestFailed(err))
        .finally(() => {
          state.loginBtn = false;
        });
    },
    onSuccess() {
      this.state.loginError = false;
      this.$message.success('密码重置成功,即将跳转登录页!');
      setTimeout(() => {
        logout(false);
        this.$router.push({ name: 'login' });
      }, 1000);
    },
    requestFailed(err) {
      this.state.loginError = true;
      this.$message.error(((err.response || {}).data || {}).message || '请求出现错误，请稍后再试');
    },
  },
};
</script>

<style scoped lang="less">
@import 'login';
.login {
  .form {
    .title {
      padding: 42px 0 16px;
    }
  }
}
</style>
